#!/usr/bin/env python3
"""
小红书推荐系统一键启动脚本
"""

import subprocess
import time
import sys
import os
import signal
from pathlib import Path

class SystemLauncher:
    """系统启动器"""
    
    def __init__(self):
        self.processes = []
        self.project_root = Path(__file__).parent.parent
    
    def check_dependencies(self):
        """检查依赖"""
        print("🔍 检查系统依赖...")
        
        # 检查Python版本
        if sys.version_info < (3, 8):
            print("❌ Python版本过低，需要3.8+")
            return False
        
        # 检查必要的包
        required_packages = [
            'fastapi', 'uvicorn', 'sqlalchemy', 'pymysql', 
            'redis', 'pyjwt', 'elasticsearch'
        ]
        
        missing_packages = []
        for package in required_packages:
            try:
                __import__(package)
            except ImportError:
                missing_packages.append(package)
        
        if missing_packages:
            print(f"❌ 缺少依赖包: {', '.join(missing_packages)}")
            print("请运行: pip install -r requirements.txt")
            return False
        
        print("✅ 依赖检查通过")
        return True
    
    def start_mysql(self):
        """启动MySQL"""
        print("🔍 检查MySQL服务...")
        
        try:
            # 尝试连接MySQL
            import pymysql
            connection = pymysql.connect(
                host='localhost',
                user='root',
                password='123456',
                database='redbook'
            )
            connection.close()
            print("✅ MySQL服务正常")
            return True
        except Exception as e:
            print(f"❌ MySQL连接失败: {e}")
            print("请确保MySQL服务已启动，并且数据库'redbook'已创建")
            return False
    
    def start_redis(self):
        """启动Redis"""
        print("🔍 检查Redis服务...")
        
        try:
            import redis
            r = redis.Redis(host='localhost', port=6379, db=0)
            r.ping()
            print("✅ Redis服务正常")
            return True
        except Exception as e:
            print(f"❌ Redis连接失败: {e}")
            print("请确保Redis服务已启动")
            return False
    
    def start_elasticsearch(self):
        """启动Elasticsearch"""
        print("🔍 检查Elasticsearch服务...")
        
        try:
            import requests
            response = requests.get('http://localhost:9200/_cluster/health', timeout=5)
            if response.status_code == 200:
                print("✅ Elasticsearch服务正常")
                return True
            else:
                print(f"❌ Elasticsearch服务异常: {response.status_code}")
                return False
        except Exception as e:
            print(f"❌ Elasticsearch连接失败: {e}")
            print("请确保Elasticsearch服务已启动")
            return False
    
    def init_database(self):
        """初始化数据库"""
        print("🔧 初始化数据库...")
        
        try:
            # 运行数据库初始化脚本
            result = subprocess.run([
                sys.executable, 'scripts/init_database.py'
            ], cwd=self.project_root, capture_output=True, text=True)
            
            if result.returncode == 0:
                print("✅ 数据库初始化成功")
                return True
            else:
                print(f"❌ 数据库初始化失败: {result.stderr}")
                return False
        except Exception as e:
            print(f"❌ 数据库初始化异常: {e}")
            return False
    
    def generate_test_data(self):
        """生成测试数据"""
        print("🔧 生成测试数据...")
        
        try:
            # 运行测试数据生成脚本
            result = subprocess.run([
                sys.executable, 'scripts/generate_test_data.py'
            ], cwd=self.project_root, input='4\n', text=True, capture_output=True)
            
            if result.returncode == 0:
                print("✅ 测试数据生成成功")
                return True
            else:
                print(f"❌ 测试数据生成失败: {result.stderr}")
                return False
        except Exception as e:
            print(f"❌ 测试数据生成异常: {e}")
            return False
    
    def setup_elasticsearch(self):
        """设置Elasticsearch"""
        print("🔧 设置Elasticsearch索引...")
        
        try:
            # 运行ES索引创建脚本
            result = subprocess.run([
                sys.executable, 'services/es_index_manager.py'
            ], cwd=self.project_root, capture_output=True, text=True)
            
            if result.returncode == 0:
                print("✅ Elasticsearch索引创建成功")
                return True
            else:
                print(f"❌ Elasticsearch索引创建失败: {result.stderr}")
                return False
        except Exception as e:
            print(f"❌ Elasticsearch设置异常: {e}")
            return False
    
    def sync_data_to_es(self):
        """同步数据到ES"""
        print("🔧 同步数据到Elasticsearch...")
        
        try:
            # 运行数据同步脚本
            result = subprocess.run([
                sys.executable, 'services/data_sync_service.py'
            ], cwd=self.project_root, capture_output=True, text=True)
            
            if result.returncode == 0:
                print("✅ 数据同步成功")
                return True
            else:
                print(f"❌ 数据同步失败: {result.stderr}")
                return False
        except Exception as e:
            print(f"❌ 数据同步异常: {e}")
            return False
    
    def start_backend(self):
        """启动后端服务"""
        print("🚀 启动后端服务...")
        
        try:
            # 启动FastAPI服务
            process = subprocess.Popen([
                sys.executable, 'main.py'
            ], cwd=self.project_root)
            
            self.processes.append(process)
            
            # 等待服务启动
            time.sleep(3)
            
            # 检查服务是否启动成功
            import requests
            try:
                response = requests.get('http://localhost:8000/health', timeout=5)
                if response.status_code == 200:
                    print("✅ 后端服务启动成功")
                    return True
                else:
                    print(f"❌ 后端服务启动失败: {response.status_code}")
                    return False
            except Exception as e:
                print(f"❌ 后端服务检查失败: {e}")
                return False
                
        except Exception as e:
            print(f"❌ 后端服务启动异常: {e}")
            return False
    
    def start_frontend(self):
        """启动前端服务"""
        print("🚀 启动前端服务...")
        
        try:
            # 切换到前端目录
            frontend_dir = self.project_root / 'redbook-ui'
            
            # 检查是否安装了依赖
            if not (frontend_dir / 'node_modules').exists():
                print("📦 安装前端依赖...")
                install_process = subprocess.run([
                    'npm', 'install'
                ], cwd=frontend_dir, capture_output=True, text=True)
                
                if install_process.returncode != 0:
                    print(f"❌ 前端依赖安装失败: {install_process.stderr}")
                    return False
            
            # 启动前端开发服务器
            process = subprocess.Popen([
                'npm', 'run', 'dev'
            ], cwd=frontend_dir)
            
            self.processes.append(process)
            
            # 等待服务启动
            time.sleep(5)
            
            print("✅ 前端服务启动成功")
            print("🌐 前端地址: http://localhost:5173")
            return True
            
        except Exception as e:
            print(f"❌ 前端服务启动异常: {e}")
            return False
    
    def run_integration_test(self):
        """运行集成测试"""
        print("🧪 运行集成测试...")
        
        try:
            result = subprocess.run([
                sys.executable, 'scripts/integration_test.py'
            ], cwd=self.project_root, input='1\n', text=True, capture_output=True)
            
            if result.returncode == 0:
                print("✅ 集成测试通过")
                return True
            else:
                print(f"❌ 集成测试失败: {result.stderr}")
                return False
        except Exception as e:
            print(f"❌ 集成测试异常: {e}")
            return False
    
    def cleanup(self):
        """清理进程"""
        print("🧹 清理进程...")
        
        for process in self.processes:
            try:
                process.terminate()
                process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                process.kill()
            except Exception as e:
                print(f"清理进程失败: {e}")
        
        self.processes.clear()
    
    def signal_handler(self, signum, frame):
        """信号处理器"""
        print("\n🛑 收到停止信号，正在清理...")
        self.cleanup()
        sys.exit(0)
    
    def launch_system(self):
        """启动整个系统"""
        print("🚀 小红书推荐系统启动器")
        print("=" * 50)
        
        # 注册信号处理器
        signal.signal(signal.SIGINT, self.signal_handler)
        signal.signal(signal.SIGTERM, self.signal_handler)
        
        try:
            # 1. 检查依赖
            if not self.check_dependencies():
                return False
            
            # 2. 检查服务
            if not self.start_mysql():
                return False
            
            if not self.start_redis():
                return False
            
            if not self.start_elasticsearch():
                return False
            
            # 3. 初始化系统
            if not self.init_database():
                return False
            
            if not self.generate_test_data():
                return False
            
            if not self.setup_elasticsearch():
                return False
            
            if not self.sync_data_to_es():
                return False
            
            # 4. 启动服务
            if not self.start_backend():
                return False
            
            if not self.start_frontend():
                return False
            
            # 5. 运行测试
            self.run_integration_test()
            
            print("=" * 50)
            print("🎉 系统启动完成！")
            print("🌐 前端地址: http://localhost:5173")
            print("🔧 后端地址: http://localhost:8000")
            print("📚 API文档: http://localhost:8000/docs")
            print("按 Ctrl+C 停止服务")
            print("=" * 50)
            
            # 保持运行
            while True:
                time.sleep(1)
                
        except KeyboardInterrupt:
            print("\n🛑 用户中断，正在停止服务...")
        except Exception as e:
            print(f"❌ 系统启动失败: {e}")
        finally:
            self.cleanup()
        
        return True

def main():
    """主函数"""
    launcher = SystemLauncher()
    
    print("=== 小红书推荐系统启动器 ===")
    print("1. 一键启动完整系统")
    print("2. 仅启动后端服务")
    print("3. 仅启动前端服务")
    print("4. 运行集成测试")
    
    choice = input("请选择操作 (1-4): ").strip()
    
    if choice == "1":
        launcher.launch_system()
    elif choice == "2":
        if launcher.check_dependencies() and launcher.start_mysql() and launcher.start_redis():
            launcher.start_backend()
    elif choice == "3":
        launcher.start_frontend()
    elif choice == "4":
        launcher.run_integration_test()
    else:
        print("无效选择")

if __name__ == "__main__":
    main()
